import React from 'react';
import style from './style.styl';
import {error} from '../';
import cx from 'classnames';
import util from '../../util';

class AutosaveTextarea extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'AutosaveTextarea';
    this.state = {
      lastValue: props.value,
      value: props.value,
      isActive: false,
      msg: '',
    }
  }
  componentDidMount() {
    this.interval = setInterval(() => {
      const {
        value,
      } = this.state;
      if(value !== this.state.lastValue) {
        this.onSave(value);
      }
    }, 1000 * 20);
  }
  componentWillUpdate(nextProps, nextState) {
    if(nextProps.value !== this.props.value) {
      this.setState({
        value: nextProps.value,
      });
    }
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }
  handleFocus = () => {
    this.setState({
      isActive: true,
    });
  }
  handleBlur = () => {
    this.setState({
      isActive: false,
    });
    const {
      value,
    } = this.state;
    if(value !== this.state.lastValue) {
      this.onSave(value);
    }
  }
  handleChange = (e) => {
    const {
      value
    } = e.target;
    this.setState({
      value,
    });
    this.props.onChange && this.props.onChange({
      value: value,
      isChange: this.state.lastValue !== value,
    });
  }
  onSave = (value) => {
    if(!value) return error('填写项不可为空');
    this.props.onSave && this.props.onSave(value);
    this.props.onChange && this.props.onChange({
      value: value,
      isChange: false,
    });
    this.setState({
      lastValue: value,
      msg: `${util.dateFormat(new Date(), 'yyyy年MM月dd日 hh:mm:ss')}已保存`,
    });
  }
  render() {
    return (
      <div className={cx({
        [style['area']]: true,
        [style['active']]: this.state.isActive,
      })}>
        <div className={style['box']}>
          <textarea
            className={style['input']}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
            onChange={this.handleChange}
            value={this.state.value}
          />
        </div> 
        <div className={style['msg']}>{this.state.msg}</div> 
      </div>
    );
  }
}

export default AutosaveTextarea;
